package com.coderfans.htmlpaser.paser;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.RecursiveTask;

/**
 * Created by ${fanchunshuai} on 2017-7-11.
 *
 * @version: V1.0
 * @Desc:
 * @Copyright (c) 2017 58到家-版权所有
 */
public class HtmlProcessor extends RecursiveTask<List<String>> {
    private String path;
    private String extension;

    public HtmlProcessor(String path, String extension) {
        this.path = path;
        this.extension = extension;
    }

    @Override
    protected List<String> compute() {
        //存储文件夹中的名称
        List<String> list = new ArrayList<String>();

        //存储子任务，这些子任务将处理文件夹中的子文件夹
        List<HtmlProcessor> tasks = new ArrayList<HtmlProcessor>();

        File file = new File(path);

        File content [] = file.listFiles();

        if(content != null){
            for (int i = 0; i < content.length; i++) {
                if(content[i].isDirectory()){
                    HtmlProcessor task = new HtmlProcessor(content[i].getAbsolutePath(), extension);
                    //如果是子文件夹，使用该方法采用异步的方式执行
                    task.fork();
                    tasks.add(task);
                }else{
                    if(checkFile(content[i].getName())){
                        list.add(content[i].getAbsolutePath());
                    }
                }
            }
        }
        if(tasks.size()> 50){
            System.out.printf("%S: %d tasks ran.\n",file.getAbsolutePath(),tasks.size());
        }
        addResultsFromTasks(list, tasks);
        return list;
    }
    //将通过这个任务而启动的子任务返回的结果增加到文件列表中，
    //参数：字符串列表list, FolderProcessor子任务列表tasks
    private void addResultsFromTasks(List<String> list,List<HtmlProcessor> tasks){
        for(HtmlProcessor  item: tasks){
            list.addAll(item.join());
        }
    }

    public boolean checkFile(String name){
        return name.endsWith(extension);
    }

}
